package com.blog.cloud.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.blog.cloud.cache.utils.RedisUtil;
import com.blog.cloud.core.exception.BlogException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

@Order(1)
@Component
public class GlobalRequestFilter implements GlobalFilter {

    @Autowired
    private RedisUtil redisUtil;

    private static final String[] whitelist = { "/auth", "/actuator"} ;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String requestUrl = request.getURI().getPath();

        // 如果请求在白名单中直接放行
        for (String path : whitelist) {
            if (requestUrl.contains(path)) {
                return chain.filter(exchange);
            }
        }

        // 如果不在白名单，则需要验证登录状态，判断token
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (StrUtil.isBlank(token)) {
            throw new BlogException("不在登录状态，请先登录");
        }

        // 如果有token，则判断token是否过期
        Object userInfo = redisUtil.get(token);
        if (Objects.isNull(userInfo)) {
            throw new BlogException("登录状态已失效，请先登录");
        }

        // 如果token有效，则表示还在登陆中，直接放行
        return chain.filter(exchange);
    }

}
